<template>
  <div>
    <el-tree
      :data="tree"
      :props="defaultProps"
      :highlight-current="true"
      :lazy="true"
      :load="loadNode"
      :expand-on-click-node="false"
      @current-change="nodeChange"
    >
        <el-tooltip slot-scope="{ node, data }"
        :open-delay="1000"
        effect="dark"
        :content="node.label === '中铁五院' ? node.label: (node.label + '(' + data.count + ')')"
        placement="top">

          <span><icon-font :icon="data.type | iconFilter" class="my-icon"></icon-font> {{ node.label === '中铁五院' ? node.label: (node.label + '(' + data.count + ')') }}</span>
        </el-tooltip>
    </el-tree>
  </div>
</template>

<script>
import { getDepartment } from '@/api/organization'
import userVue from '../settings/user.vue'

// :default-expanded-keys="[1]"
export default {
  data() {
    return {
      tree: [],
      rootNode: null,
      defaultProps: {
        children: 'children',
        label: 'name',
        isLeaf: 'leaf',
      },
      selectedNode: null
    }
  },
  mounted() {
    // 默认展开根节点
    this.rootNode.childNodes[0].checked = true
    this.rootNode.childNodes[0].expanded = true
    this.rootNode.childNodes[0].loadData()
  },
  filters: {
    // 根据节点种类，显示不同的图标
    iconFilter(type) {
      if (type === 'department') return 'department'
      else if (type === 'user') return 'user'
      return ''
    },
  },
  methods: {
    async loadNode(node, resolve) {
      if (node.level === 0) { // 第一次自动触发方法时，加入公司
        resolve([{ id: 1, name: '中铁五院', type: 'department' }])
        this.rootNode = node
        return
      }
      let { data } = await getDepartment(node.data.id)
      resolve(data.children)
    },
    nodeChange(node) {
      this.selectedNode = node
      this.$emit('changeNode', node)
    },
    modifyNode(entity) {
      this.selectedNode.name = entity.name
      this.selectedNode.sort = entity.sort
    }
  },
}
</script>

<style lang="scss" scoped>
.my-icon {
  margin-right: 4px;
}
</style>
